from fastapi import APIRouter, UploadFile, File
from bs4 import BeautifulSoup
import tempfile
import os

import logging

from common.response.response_code import CustomResponseCode as HttpCode
from common.response.response_schema import response_base, simple_response

router = APIRouter()


def parse_favor_html(content):
    """
    解析浏览器收藏夹导出内容
    :param content: html内容
    :return:
    """
    bookmarks = []
    soup = BeautifulSoup(content, "html.parser")
    links = soup.find_all("a")
    for link in links:
        url = link.get('href')
        title = link.get_text()
        bookmarks.append({"title": title, "url": url})
    return bookmarks


@router.post("/import_html")
async def import_favor_html(file: UploadFile = File(...)):
    parse_res = []
    # Step 1: 创建临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as temp_file:
        temp_file_name = temp_file.name
        content = await file.read()  # 读取文件内容
        temp_file.write(content)  # 写入到临时文件中

    # Step 2: 解析 HTML 文件
    with open(temp_file_name, "r", encoding="utf-8") as html_file:
        parse_res = parse_favor_html(html_file)

    # Step 3: 删除临时文件
    os.remove(temp_file_name)

    resp_data = {
        "content": parse_res,
        "count": len(parse_res)
    }

    # Step 4: 返回解析结果
    return simple_response(data=resp_data)
